#include "visibilitymeterform.h"
#include "ui_visibilitymeterform.h"

#include <QGraphicsDropShadowEffect>
#include <QDateTimeAxis>
#include <QDateTime>
#include <QLegend>
#include <QLegendMarker>
#include <QStandardItemModel>
#include <QTableView>

#include "../deviceClass/visibility.h"

VisibilityMeterForm::VisibilityMeterForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::VisibilityMeterForm)
{
    ui->setupUi(this);

    this->InitChart();
    this->InitTreeView();

    this->m_startTime = QDateTime::currentDateTime();
    //Visibility解析数据后，连接所有的需要展示数据的地方，
    //右下角的一分钟能见度
    connect(Visibility::getInstance(), &Visibility::updateView,
            ui->widget_progress, &CircleProgressBar::Slot_UpdateValue);
    //
    connect(Visibility::getInstance(), &Visibility::updateView,
            this, [=](const VisibilityProtocolAll& protocol){
        ui->label_energy_intisity->setText(QString::number(protocol.TheIntensityOfEmittedEnergy));

    });


    //启动按钮
    connect(ui->pushButton_pause, &QPushButton::clicked, this, [&](){
        m_thread = QThread::create([&](){
            while(true){
                if ( QThread::currentThread()->isInterruptionRequested()) {
                    return;
                }
                quint32 value1 = QRandomGenerator::global()->bounded(20000, 40000);
                quint32 value2 = QRandomGenerator::global()->bounded(30000, 40000);
                quint32 value3 = QRandomGenerator::global()->bounded(10000, 20000);
                quint32 value4 = QRandomGenerator::global()->bounded(2, 4);
                quint32 value5 = QRandomGenerator::global()->bounded(50, 59);
                QList<QString> codes = {"00110100", "00110001", "00110010"};
                VisibilityProtocol protocol = {
                    .one_minute_visibility = (int)value1,
                    .ten_minute_visibility = (int)value2,
                    .TheIntensityOfEmittedEnergy = (int)value3,
                    .TheIntensityOfReceivedEnergy = (int)value4,
                    .RatedPower = (int)value5,
                    .device_code = codes.at(QRandomGenerator::global()->bounded(0, 2)),
                    .date_time = QDateTime::currentDateTime()
                };
                emit this->updateView(protocol);
                QThread::msleep(1000);
            }

        });
        connect(m_thread, &QThread::finished, m_thread, &QThread::deleteLater);
        m_thread->start();

        ui->label_start_time->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
        ui->label_start_time->update();

        ui->label_end_time->setText("0000-00-00 00:00:00");
        ui->label_end_time->update();

        ui->pushButton_pause->setEnabled(false);
    });

    connect(ui->pushButton_close, &QPushButton::clicked, this, [&](){
        ui->label_end_time->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
        ui->label_end_time->update();
        ui->pushButton_pause->setEnabled(true);
        m_thread->quit();
    });

    connect(ui->pushButton_back, &QPushButton::clicked, this, [&](){
        //back
    });

    // connect(this, &VisibilityMeterForm::updateView, this, [&](VisibilityProtocol protocol){
    //     ui->label_rated_power->setText(QString::asprintf("%d", protocol.RatedPower));
    //     ui->label_rated_power->update();
    //     ui->label_energy_intisity->setText(QString::asprintf("%d", protocol.TheIntensityOfEmittedEnergy));
    //     ui->label_energy_intisity->update();
    //     ui->label_start_time->setText(this->m_startTime.toString("yyyy-MM-dd HH:mm:ss"));
    //     ui->label_start_time->update();
    // });

    // connect(this, &VisibilityMeterForm::updateView,
    //         ui->widget_progress, &CircleProgressBar::Slot_UpdateValue);

    // connect(this, &VisibilityMeterForm::updateView, ui->label_spendtime, [=, this](VisibilityProtocol point){
    //     int days    = point.date_time.date().day() - m_startTime.date().day();
    //     int hours   = point.date_time.time().hour() - m_startTime.time().hour();
    //     int minutes = point.date_time.time().minute() - m_startTime.time().minute();
    //     int seconds = point.date_time.time().second() - m_startTime.time().second();
    //     ui->label_spendtime->setText(QString::asprintf("%d天-%d时-%d分-%d秒", days, hours, minutes, seconds));
    //     ui->label_spendtime->update();
    // });
}

VisibilityMeterForm::~VisibilityMeterForm()
{
    delete ui;
}

//能见度仪展示数据界面的图表
#include <QPalette>
void VisibilityMeterForm::InitTreeView()
{
    ui->tableView->setWindowTitle("数据列表");
    ui->tableView->setWindowIconText("数据列表");
    m_model.setRowCount(0);
    m_model.setColumnCount(6);
    m_model.setHorizontalHeaderLabels(QStringList() << "1分钟能见度"
                                                    << "10分钟能见度"<<"发射能量强度"
                                                    <<"接收能量强度"<<"设备状态码"<<"时间");

    QHeaderView *headerView = ui->tableView->horizontalHeader();
    // 设置样式表，包括背景颜色和字体样式
    headerView->setSectionResizeMode(QHeaderView::ResizeMode::Stretch);
    headerView->setStyleSheet("QHeaderView::section { background-color: #8da1ff; color: white }");
    headerView->setTextElideMode(Qt::TextElideMode::ElideMiddle);

    ui->tableView->setModel(&m_model);
    //更新 图表


    connect(Visibility::getInstance(), &Visibility::updateView, this, [&](const VisibilityProtocolAll& point){
        int row = m_model.rowCount();
        if(row == 10){
            m_model.removeRows(0, 1);
            row--;
        }

        auto item = new QStandardItem(QString::asprintf("%d",point.one_minute_visibility));
        item->setTextAlignment(Qt::AlignCenter);
        m_model.setItem(row, 0, item);

        item = new QStandardItem(QString::asprintf("%d",point.ten_minute_visibility));
        item->setTextAlignment(Qt::AlignCenter);
        m_model.setItem(row, 1, item);

        item = new QStandardItem(QString::asprintf("%d",point.TheIntensityOfEmittedEnergy));
        item->setTextAlignment(Qt::AlignCenter);
        m_model.setItem(row, 2, item);

        item = new QStandardItem(QString::asprintf("%d",point.TheIntensityOfReceivedEnergy));
        item->setTextAlignment(Qt::AlignCenter);
        m_model.setItem(row, 3, item);

        item = new QStandardItem(point.deviceState);
        item->setTextAlignment(Qt::AlignCenter);
        m_model.setItem(row, 4, item);

        item = new QStandardItem(point.date_time.toString("yyyy/MM/dd HH:mm:ss"));
        item->setTextAlignment(Qt::AlignCenter);
        m_model.setItem(row, 5, item);

        ui->tableView->update();
    });
}


void VisibilityMeterForm::InitChart()
{

    this->m_visYMax.clear(); this->m_visYMax.push_back(INT_MIN);
    this->m_visYMin.clear(); this->m_visYMin.push_back(INT_MAX);
    m_chart = new QChart();

    QSplineSeries* m_series1 = new QSplineSeries(m_chart);
    m_series1->setPen(QPen(QBrush(Qt::blue),2, Qt::PenStyle::SolidLine,
                           Qt::PenCapStyle::RoundCap, Qt::PenJoinStyle::RoundJoin));

    QSplineSeries* m_series10 = new QSplineSeries(m_chart);
    m_series10->setPen(QPen(QBrush(Qt::green),2, Qt::PenStyle::SolidLine,
                            Qt::PenCapStyle::RoundCap, Qt::PenJoinStyle::RoundJoin));

    m_chart->addSeries(m_series1);
    m_chart->addSeries(m_series10);

    // 更改标题颜色和字体大小
    QFont titleFont("sans-serif", 12, QFont::Bold);
    m_chart->setTitleFont(titleFont);
    QBrush titleBrush(Qt::black);
    m_chart->setTitleBrush(titleBrush);

    // 设置y轴
    QValueAxis *axisY = new QValueAxis();
    axisY->setRange(0, 50000);
    axisY->setTickCount(6);
    axisY->setLabelFormat("%d");

    // 设置x轴
    QDateTimeAxis* axisX = new QDateTimeAxis;
    axisX->setTickCount(10);
    axisX->setFormat("hh:mm:ss");
    axisX->setRange(QDateTime::currentDateTime().addSecs(-60), QDateTime::currentDateTime().addMSecs(500));

    m_chart->addAxis(axisX, Qt::AlignBottom);
    m_chart->addAxis(axisY, Qt::AlignmentFlag::AlignLeft);

    m_series1->attachAxis(axisX);
    m_series1->attachAxis(axisY);

    m_series10->attachAxis(axisX);
    m_series10->attachAxis(axisY);

    m_chart->legend()->markers().at(0)->setVisible(true);
    m_chart->legend()->markers().at(0)->setFont(QFont("微软雅黑",12));
    m_chart->legend()->markers().at(0)->setPen(QPen(Qt::blue));
    m_series1->setName("一分钟能见度");

    m_chart->legend()->markers().at(1)->setVisible(true);
    m_chart->legend()->markers().at(1)->setFont(QFont("微软雅黑",12));
    m_chart->legend()->markers().at(1)->setPen(QPen(Qt::green));
    m_series10->setName("十分钟能见度");


    m_chart->legend()->attachToChart();

    ui->graphicsView->setChart(m_chart);
    ui->graphicsView->setRenderHint(QPainter::Antialiasing);



    connect(Visibility::getInstance(), &Visibility::updateView, this, [=](const VisibilityProtocolAll& point){
        m_series1->append(point.date_time.toMSecsSinceEpoch(), point.one_minute_visibility);
        m_series10->append(point.date_time.toMSecsSinceEpoch(), point.ten_minute_visibility);
        //进数据，维护数组m_visYMax和m_visYMin
        int tempMax = std::max(point.one_minute_visibility, point.ten_minute_visibility);
        int tempMin = std::min(point.one_minute_visibility, point.ten_minute_visibility);
        if(!this->m_visYMax.empty() && tempMax > this->m_visYMax[0]){
            this->m_visYMax.clear();
        }
        else if(!this->m_visYMax.empty() && tempMax <= this->m_visYMax[0]){
            //删除数组中小于tempMax的值
            for(int i = 1; i < this->m_visYMax.size();){
                if(this->m_visYMax[i] < tempMax){
                    this->m_visYMax.remove(i);
                }else{
                    ++i;
                }
            }
        }
        this->m_visYMax.push_back(tempMax);

        if(!this->m_visYMin.empty() && tempMin < this->m_visYMin[0]){
            this->m_visYMin.clear();
        }
        else if(!this->m_visYMin.empty() && tempMin >= this->m_visYMin[0]){
            //删除数组中大于tempMin的值
            for(int i = 1; i < this->m_visYMin.size();){
                if(this->m_visYMin[i] > tempMin){
                    this->m_visYMin.remove(i);
                }else{
                    ++i;
                }
            }
        }
        this->m_visYMin.push_back(tempMin);


        if(m_series1->count() > 60 && m_series10->count() > 60){
            //出队的时候维护数组
            int tempMin = std::min(m_series1->at(0).y(), m_series10->at(0).y());
            int tempMax = std::max(m_series1->at(0).y(), m_series10->at(0).y());
            if(tempMax == this->m_visYMax[0]){
                this->m_visYMax.pop_front();
            }
            if(tempMin== this->m_visYMin[0]){
                this->m_visYMin.pop_front();
            }
            m_series1->removePoints(0, m_series1->count() - 60);
            m_series10->removePoints(0, m_series10->count() - 60);
        }

        QDateTime start = point.date_time.addSecs(-3600);
        QDateTime end = point.date_time.addMSecs(500);
        axisX->setRange(start, end);
        axisY->setRange(m_visYMin[0] - 1000, m_visYMax[0] + 1000);
        ui->graphicsView->update();
    });

    /*connect(this, &VisibilityMeterForm::updateView, this, [&](VisibilityProtocol point){

        // m_series1->append(point.date_time.toMSecsSinceEpoch(), point.one_minute_visibility);
        // m_series10->append(point.date_time.toMSecsSinceEpoch(), point.ten_minute_visibility);
        // //进数据，维护数组m_visYMax和m_visYMin
        // int tempMax = std::max(point.one_minute_visibility, point.ten_minute_visibility);
        // int tempMin = std::min(point.one_minute_visibility, point.ten_minute_visibility);
        // if(!this->m_visYMax.empty() && tempMax > this->m_visYMax[0]){
        //     this->m_visYMax.clear();
        // }
        // else if(!this->m_visYMax.empty() && tempMax <= this->m_visYMax[0]){
        //     //删除数组中小于tempMax的值
        //     for(int i = 1; i < this->m_visYMax.size();){
        //         if(this->m_visYMax[i] < tempMax){
        //             this->m_visYMax.remove(i);
        //         }else{
        //             ++i;
        //         }
        //     }
        // }
        // this->m_visYMax.push_back(tempMax);

        // if(!this->m_visYMin.empty() && tempMin < this->m_visYMin[0]){
        //     this->m_visYMin.clear();
        // }
        // else if(!this->m_visYMin.empty() && tempMin >= this->m_visYMin[0]){
        //     //删除数组中大于tempMin的值
        //     for(int i = 1; i < this->m_visYMin.size();){
        //         if(this->m_visYMin[i] > tempMin){
        //             this->m_visYMin.remove(i);
        //         }else{
        //             ++i;
        //         }
        //     }
        // }
        // this->m_visYMin.push_back(tempMin);


        // if(m_series1->count() > 60 && m_series10->count() > 60){
        //     //出队的时候维护数组
        //     int tempMin = std::min(m_series1->at(0).y(), m_series10->at(0).y());
        //     int tempMax = std::max(m_series1->at(0).y(), m_series10->at(0).y());
        //     if(tempMax == this->m_visYMax[0]){
        //         this->m_visYMax.pop_front();
        //     }
        //     if(tempMin== this->m_visYMin[0]){
        //         this->m_visYMin.pop_front();
        //     }
        //     m_series1->removePoints(0, m_series1->count() - 60);
        //     m_series10->removePoints(0, m_series10->count() - 60);
        // }

        // QDateTime start = point.date_time.addSecs(-3600);
        // QDateTime end = point.date_time.addMSecs(500);
        // axisX->setRange(start, end);
        // axisY->setRange(m_visYMin[0] - 1000, m_visYMax[0] + 1000);
        // ui->graphicsView->update();
    });*/
}













